const express = require('express')
const router = express.Router()
const { verifyToken } = require('../../middilWare/verifyToken')
const {
  createManager,
  getManager,
  updateManagerPassword,
  updateManagerInfo,
  deleteManager,
  getAllManagers,
  managerLogin,
} = require('../../services/managerService')
const jwt = require('jsonwebtoken')
const SECRET_KEY = 'my_super_secret_2024'

// 执法人员注册
router.post('/register', async (req, res) => {
  try {
    const manager = await createManager(req.body)
    if (manager) {
      res.status(200).json({ code: 200, message: 'manager register success' })
    } else {
      res.status(400).json({ code: 400, message: 'manager register error' })
    }
  } catch (err) {
    res.status(500).json({ code: 500, message: 'register error' })
  }
})

// 执法人员登录
router.post('/login', async (req, res) => {
  try {
    const { userName, password } = req.body
    const manager = await managerLogin(userName, password)
    if (manager) {
      const token = jwt.sign(
        { id: manager.id, name: manager.userName, role: 'manager' },
        SECRET_KEY,
        { expiresIn: '7d' }
      )
      res
        .status(200)
        .json({
          code: 200,
          message: 'login success',
          manager,
          token,
          juri: manager.juri,
        })
    } else {
      res.status(400).json({ code: 400, message: 'username or password error' })
    }
  } catch (err) {
    res.status(500).json({ code: 500, message: 'login error' })
  }
})

// 获取所有执法人员（需token）
router.get('/', verifyToken, async (req, res) => {
  const managers = await getAllManagers()
  res.json({ code: 200, managers })
})

module.exports = router
